package business

import (
	"ginBasic/app"
	"ginBasic/app/common/lib"
	"ginBasic/app/common/model"
	"ginBasic/app/common/model/filter"
)

var Access = new(AccessBus)

type AccessBus struct {
	BaseBus
}

func (b AccessBus) GetList(req *filter.AccessFilterReq) ([]*filter.AccessNode, int, error) {
	where := "1=1"

	if req != nil {
		if req.ModuleName != "" {
			where += " AND module_name like '%" + req.ModuleName + "%'"
		}
		if req.Type != 0 {
			reqType := lib.String(req.Type)
			where += " AND type=" + reqType
		}
		if req.Url != "" {
			where += " AND url like '%" + req.Url + "%'"
		}
	}
	accessList := model.AccessModel.List(where)
	List := make([]*filter.AccessNode, 0)
	for _, v := range accessList {
		List = append(List, &filter.AccessNode{
			Id:       v.Id,
			ParentId: v.ModuleId,
			Type:     v.Type,
			Url:      v.Url,
			VIcon:    v.Icon,
			Sort:     v.Sort,
			Status:   v.Status,
			Name:     v.ModuleName,
			Children: nil,
			IsParent: false,
		})
	}
	userList := b.GetTreeRecursive(List, 0)
	if !app.IsStructEmpty(userList) && List != nil {
		return List, 0, nil
	}
	return userList, 0, nil
}

func (b AccessBus) GetTreeRecursive(list []*filter.AccessNode, parentId int) []*filter.AccessNode {
	res := make([]*filter.AccessNode, 0)
	for _, v := range list {
		if v.ParentId == parentId {
			v.Children = b.GetTreeRecursive(list, v.Id)
			if app.IsStructEmpty(v.Children) {
				v.IsParent = true
			}
			res = append(res, v)
		}
	}
	return res
}

func (b AccessBus) Add(req *model.Access) (bool, error) {
	_, err := model.AccessModel.Add(req)
	if err != nil {
		return false, err
	}
	return true, nil
}

func (b AccessBus) GetInfoById(id int) model.Access {
	accessInfo := model.Access{}
	accessInfo = model.AccessModel.GetInfoById(id)
	return accessInfo
}

func (b AccessBus) Edit(req *model.Access) (bool, error) {
	_, err := model.AccessModel.Edit(req)
	if err != nil {
		return false, err
	}
	return true, nil
}

func (b AccessBus) Delete(id int) error {
	res, err := model.AccessModel.Delete(id)
	if res {
		return nil
	} else {
		return err
	}
}
